package com.sceneworker.util.xml;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

abstract public class GenericXMLLoader extends DefaultHandler
{
//	 simple string buffer
	private StringBuffer 		mcl_buffer;
	
	public	GenericXMLLoader() {
	}
	
	
	@Override
	public void 
	startElement(String str_namespace, String str_simpleName,
			String str_qualifiedName, Attributes cl_attrs)
	throws SAXException
	{
		String lstr_elementName = str_simpleName;

		if ("".equals(lstr_elementName))
		{
			lstr_elementName = str_qualifiedName;
		}
		
		//System.out.println("tag = " + lstr_elementName);
		handleStartTag(lstr_elementName, cl_attrs);
		
		mcl_buffer = null;
	}
	
	abstract	public	void
	handleStartTag(String str_tag, Attributes cl_attrs);
	
	@Override
	public void 
	endElement(String str_nameSpace, String str_simpleName,
			String str_qualifiedName)
	throws SAXException
	{
		String lstr_elementName = str_simpleName;

		if ("".equals(lstr_elementName))
		{
			lstr_elementName = str_qualifiedName;
		}

		String lstr_temp; //= "" + mcl_buffer;

		if (mcl_buffer == null)
		{
			lstr_temp = "";
		}
		else
		{
			lstr_temp = "" + mcl_buffer;
		}
		
		handleEndTag(lstr_elementName, lstr_temp);
		
//		 clear buffer
		mcl_buffer = null;
	}
	
	abstract	public	void	handleEndTag(String str_tag, String str_tagData);

	@Override
	public void	characters(char str_buf[], int i_offset, int i_length)
	throws SAXException
	{
		String lstr_temp = new String(str_buf, i_offset, i_length);

		if (mcl_buffer == null)
		{
			mcl_buffer = new StringBuffer(lstr_temp);
		}
		else
		{
			mcl_buffer.append(lstr_temp);
		}
	}
	
	static	public	void	loadXMLFile(String str_mapLoc, GenericXMLLoader cl_loader, boolean b_jarExe)
	{
		// load the map xml file
		DefaultHandler  lcl_handler = cl_loader;

		SAXParserFactory    lcl_factory = SAXParserFactory.newInstance();

		try
		{
			SAXParser   lcl_saxParser = lcl_factory.newSAXParser();
			
			if(!b_jarExe) {
				File    lcl_inFile = new File(str_mapLoc);

				lcl_saxParser.parse(lcl_inFile, lcl_handler);

			}
			else {
				URL		lcl_url = GenericXMLLoader.class.getResource("/" + str_mapLoc);
				System.out.println("url = " + lcl_url);
				InputStream		lcl_inFile = lcl_url.openStream();
				
				lcl_saxParser.parse(lcl_inFile, lcl_handler);
			}
					
		}
		catch(Throwable cl_t)
		{
			cl_t.printStackTrace();
		}
	}
	
	static	public	void	loadXMLFile(URL cl_loc, GenericXMLLoader cl_loader) {
		DefaultHandler  lcl_handler = cl_loader;
		SAXParserFactory    lcl_factory = SAXParserFactory.newInstance();

		try	{
			SAXParser   lcl_saxParser = lcl_factory.newSAXParser();
			InputStream		lcl_inFile = cl_loc.openStream();
			lcl_saxParser.parse(lcl_inFile, lcl_handler);		
		}
		catch(Throwable cl_t) {
			cl_t.printStackTrace();
		}
	}
}
